/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import {
    warn,
    assetManager,
    AssetManager,
    SpriteFrame,
    Asset,
    Texture2D,
    resources,
    JsonAsset,
    Prefab,
    TTFFont,
    AudioClip,
    __private,
    LabelAtlas,
    SpriteAtlas,
    BitmapFont,
    Font,
    Mesh,
    Skeleton,
    BufferAsset,
    SceneAsset,
    TextAsset,
    ImageAsset,
    EffectAsset,
    Material,
    Script,
    AnimationClip,
    ParticleAsset,
    PhysicsMaterial,
    TerrainAsset,
    TiledMapAsset,
    VideoClip,
    dragonBones,
    sp
} from 'cc';
import { asyncIO } from './async';

const TAG = 'lcc/core/asset.ts';

/**
 * @zh
 * 加载远程资源，一般是图片
 *
 * @param url - 资源路径
 */
export function loadRemote<T extends Asset>(url: string) {
    return new Promise<T>((resolve) => {
        asyncIO.inc();
        assetManager.loadRemote(url, (err: Error | null, data: T) => {
            asyncIO.dec();
            if (!err && data) {
                resolve(data);
            } else {
                warn(TAG, `not found remote asset : ${url}`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 加载远程精灵帧
 *
 * @param url - 精灵帧URL路径
 */
export async function loadRemoteSpriteFrame(url: string) {
    let asset = await loadRemote(url);
    if (asset) {
        let spriteFrame = new SpriteFrame();
        spriteFrame.texture = asset as Texture2D;
        return spriteFrame;
    }
}

/**
 * @zh
 * 加载资源包
 *
 * @param nameOrUrl - 包名或者URL路径
 */
export function loadBundle(
    nameOrUrl: string,
    options: __private._cocos_core_asset_manager_shared__IBundleOptions | null = null
) {
    return new Promise<AssetManager.Bundle>((resolve) => {
        asyncIO.inc();
        assetManager.loadBundle(nameOrUrl, options, (err, bundle) => {
            asyncIO.dec();
            if (!err && bundle) {
                resolve(bundle);
            } else {
                warn(TAG, `not found bundle : '${nameOrUrl}'`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 通过UUID加载资源
 *
 * @param uuid - UUID
 */
export function loadAssetByUUID<T extends Asset>(uuid: string) {
    return new Promise<T>((resolve) => {
        asyncIO.inc();
        assetManager.loadAny([uuid], (err, asset: T) => {
            asyncIO.dec();
            if (!err && asset) {
                resolve(asset);
            } else {
                warn(TAG, `not found asset : '${uuid}'`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 加载资源
 *
 * @param path 资源路径
 * @param type 资源类型
 * @param bundle - 包对象
 */
export function loadAsset<T extends Asset>(
    path: string,
    type: __private._cocos_core_asset_manager_shared__AssetType<T>,
    bundle: AssetManager.Bundle = resources
) {
    return new Promise<T>((resolve) => {
        asyncIO.inc();
        bundle.load(path, type, (err, data) => {
            asyncIO.dec();
            if (!err && data) {
                resolve(data);
            } else {
                warn(TAG, `not found asset '${path}' in '${bundle.name}'`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 加载 SpriteAtlas
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadSpriteAtlas(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, SpriteAtlas, bundle);
}

/**
 * @zh
 * 加载 TTFFont
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadTTFFont(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, TTFFont, bundle);
}

/**
 * @zh
 * 加载 LabelAtlas
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadLabelAtlas(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, LabelAtlas, bundle);
}

/**
 * @zh
 * 加载 BitmapFont
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadBitmapFont(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, BitmapFont, bundle);
}

/**
 * @zh
 * 加载 Font
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadFont(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Font, bundle);
}

/**
 * @zh
 * 加载 SpriteFrame
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadSpriteFrame(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, SpriteFrame, bundle);
}

/**
 * @zh
 * 加载 Mesh
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadMesh(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Mesh, bundle);
}

/**
 * @zh
 * 加载 Skeleton
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadSkeleton(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Skeleton, bundle);
}

/**
 * @zh
 * 加载 AudioClip
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadAudioClip(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, AudioClip, bundle);
}

/**
 * @zh
 * 加载 BufferAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadBufferAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, BufferAsset, bundle);
}

/**
 * @zh
 * 加载 Prefab
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadPrefab(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Prefab, bundle);
}

/**
 * @zh
 * 加载 SceneAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadSceneAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, SceneAsset, bundle);
}

/**
 * @zh
 * 加载 TextAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export async function loadTextAsset(path: string, bundle: AssetManager.Bundle = resources) {
    let textAsset = await loadAsset(path, TextAsset, bundle);
    return textAsset?.text;
}

/**
 * @zh
 * 加载 JsonAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export async function loadJsonAsset(path: string, bundle: AssetManager.Bundle = resources) {
    let jsonAsset = await loadAsset(path, JsonAsset, bundle);
    return jsonAsset?.json;
}

/**
 * @zh
 * 加载 ImageAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadImageAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, ImageAsset, bundle);
}

/**
 * @zh
 * 加载 EffectAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadEffectAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, EffectAsset, bundle);
}

/**
 * @zh
 * 加载 Material
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadMaterial(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Material, bundle);
}

/**
 * @zh
 * 加载 Script
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadScript(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, Script, bundle);
}

/**
 * @zh
 * 加载 AnimationClip
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadAnimationClip(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, AnimationClip, bundle);
}

/**
 * @zh
 * 加载 ParticleAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadParticleAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, ParticleAsset, bundle);
}

/**
 * @zh
 * 加载 PhysicsMaterial
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadPhysicsMaterial(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, PhysicsMaterial, bundle);
}

/**
 * @zh
 * 加载 TerrainAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadTerrainAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, TerrainAsset, bundle);
}

/**
 * @zh
 * 加载 TiledMapAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadTiledMapAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, TiledMapAsset, bundle);
}

/**
 * @zh
 * 加载 VideoClip
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadVideoClip(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, VideoClip, bundle);
}

/**
 * @zh
 * 加载 dragonBones.DragonBonesAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadDragonBonesAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, dragonBones.DragonBonesAsset, bundle);
}

/**
 * @zh
 * 加载 dragonBones.DragonBonesAtlasAsset
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadDragonBonesAtlasAsset(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, dragonBones.DragonBonesAtlasAsset, bundle);
}

/**
 * @zh
 * 加载 sp.SkeletonData
 *
 * @param path 资源路径
 * @param bundle 包对象
 */
export function loadSkeletonData(path: string, bundle: AssetManager.Bundle = resources) {
    return loadAsset(path, sp.SkeletonData, bundle);
}
